package com.inspur.sc.springboot.security;

import com.alibaba.fastjson.JSONObject;
import com.inspur.sc.springboot.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yuchu
 */
@Service
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        boolean isAjax = isAjaxRequest(request);
        if (!isAjax) {
            request.setAttribute("isAjaxRequest", isAjax);
            request.setAttribute("message", e.getMessage());
            RequestDispatcher dispatcher = request.getRequestDispatcher("/403");
            dispatcher.forward(request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json");
            ResponseVO responseVO = new ResponseVO();
            responseVO.setMessage("没有该权限或没有登录，请联系管理员！");
            responseVO.setCode(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(JSONObject.toJSONString(responseVO));
            response.getWriter().close();
        }

    }

    public boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return header != null && "XMLHttpRequest".equals(header);
    }
}
